<template>
  <!-- v-bind="$attrs" 绑定父组件传递过来的 el-menu 属性 -->
  <el-menu :collapse="collapse" router background-color="#545c64" active-text-color="#ffd04b" text-color="#ffff" style="width: 200px;" :default-active="active" v-bind="$attrs">
    <!-- 无数据时,使用默认菜单 -->
    <template v-for="r in data ? data : routeMenu" :key="r.index">
      <!-- 只有一级路由 -->
      <el-menu-item v-if="!r.children || !r.children.length" :index="r.index">
        <template #title>
          <component :is="r.icon" />
          <span>{{ r.title }}</span>
        </template>
      </el-menu-item>
      <!-- 有子路由 -->
      <el-sub-menu v-else :index="r.index">
        <template #title>
          <component :is="r.icon" />
          <span>{{ r.title }}</span>
        </template>
        <!-- 二级子菜单 -->
        <el-menu-item v-for="child in r.children" :index="r.index + '/' + child.index">
          <template #title>
            <component :is="child.icon" />
            <span>{{ child.title }}</span>
          </template>
        </el-menu-item>
      </el-sub-menu>
    </template>
  </el-menu>
</template>

<script setup lang="ts">
import { PropType, computed, onMounted, ref } from 'vue'
import { MenuItem } from './types'
import { useRouter } from 'vue-router'

let router = useRouter()

const routeMenu = computed(() => {
  var rs: MenuItem[] = []
  router.options.routes
    .filter(item => item.path != '/')
    .forEach((r, i, c) => {
      let tmp = {
        index: r.path,
        icon: r.meta?.icon as string,
        title: r.meta?.title as string,
        children: [] as MenuItem[],
      }
      if (r.children) {
        r.children.forEach(child =>
          tmp.children.push({
            index: child.path,
            icon: child.meta?.icon as string,
            title: child.meta?.title as string,
          }),
        )
      }
      rs.push(tmp)
    })
  return rs
})

let props = defineProps({
  data: {
    type: Array as PropType<MenuItem[]>,
  },
  defaultActive: {
    type: String,
    default: '',
  },
  collapse: {
    type: Boolean,
    default: false,
  },
})

let active = ref(props.defaultActive)

onMounted(() => {
  if (props.defaultActive) {
    if (router.currentRoute.value.path == '/') {
      router.push(props.defaultActive)
      active.value = props.defaultActive
    } else {
      active.value = router.currentRoute.value.path
    }
  }
})
</script>

<style lang="scss" scoped>
.el-menu {
  height: 100%;
}

svg {
  width: 1.2em;
  height: 1.2em;
  margin-right: 4px;
}
</style>
